package com.threegroup.web.controller;

import com.threegroup.common.utils.Result;
import com.threegroup.common.validator.ValidatorUtils;
import com.threegroup.web.annotation.Login;
import com.threegroup.web.dto.LoginDTO;
import com.threegroup.web.service.TokenService;
import com.threegroup.web.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 登录接口
 */
@RestController
@RequestMapping("/mp")
@Slf4j
public class ApiLoginController {

    @Resource
    private UserService userService;

    @Resource
    private TokenService tokenService;

    /**
     * 用户登录
     * @param loginDTO
     * @return
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody LoginDTO loginDTO) {

        // 表单验证
        ValidatorUtils.validateEntity(loginDTO);

        // 用户登录
        Map<String, Object> map = userService.login(loginDTO);

        return new Result<Map<String, Object>>().ok(map);
    }


    @Login
    @PostMapping("wxGetPhone")
    public Result<String> wxGetPhone(@RequestBody LoginDTO dto) {

        String phone = userService.wxGetPhone(dto);

        return new Result().ok(phone);
    }

    @Login
    @PostMapping("logout")
    public Result logout( @RequestAttribute(value = "userId", required = false) Long userId){
        if (userId != null) {
            tokenService.expireToken(userId);
        }
        return new Result();
    }

}
